package com.example.widget.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.example.widget.R;

public class AnchorLinerBehavior extends CoordinatorLayout.Behavior<View> {
    private Context context;
    private int anchorId;

    public AnchorLinerBehavior(Context context, AttributeSet attrs) {
        this.context = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.anchor_behavior, 0, 0);
        anchorId = typedArray.getResourceId(R.styleable.anchor_behavior_anchorId,0);
        typedArray.recycle();
    }
    @Override
    public boolean onMeasureChild(@NonNull CoordinatorLayout parent, @NonNull View child,
                                  int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        View anchorView = parent.findViewById(anchorId);
        if (anchorView == null)
            return false;
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        int top = lp.topMargin;//获取顶部外边距
        int startTop = anchorView.getBottom()+top;
        parent.onMeasureChild(child,parentWidthMeasureSpec,widthUsed,parentHeightMeasureSpec,startTop);
        return true;
    }

    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
        View anchorView = parent.findViewById(anchorId);
        if (anchorView == null)
            return false;
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        int top = lp.topMargin;//获取顶部外边距
        int bottom = anchorView.getBottom();
        parent.onLayoutChild(child,layoutDirection);
        //设置子控件摆放位置偏移
        child.offsetTopAndBottom(top+bottom);
        return true;
    }
    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        return dependency.getId() == anchorId;
    }
}
